//
//  MXCommentsView.m
//  CatchBear
//
//  Created by 王启颖 on 2018/12/10.
//  Copyright © 2018年 王启颖. All rights reserved.
//

#import "MXCommentsView.h"
#import "MXCommentsCell.h"
#import "MXCommentsModel.h"

@interface MXCommentsView () <UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic ,strong) UITableView *tableView;
@property (strong, nonatomic) UITextField *textField;

@property (strong, nonatomic) NSMutableArray *paramsArr;

@property (nonatomic, assign) int currentPage;

@property (strong, nonatomic) NSMutableDictionary *dicParams;
@property (strong, nonatomic) NSMutableDictionary *sendDicParams;

@end

@implementation MXCommentsView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - KSafeAreaTopHeight - 44)];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.backgroundColor = MX_GRAY_COLOR;
        self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        self.tableView.estimatedRowHeight = 100;
        self.tableView.rowHeight=UITableViewAutomaticDimension;
        self.tableView.estimatedSectionHeaderHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        [self addSubview:self.tableView];
        
        [self addHeaderRefresh];
        
        
        self.textField = [[UITextField alloc]initWithFrame:CGRectMake(20, 5, kScreenWidth - 20 - 84, 34)];
        self.textField.delegate = self;
        self.textField.placeholder = @"发表评论";
        self.textField.backgroundColor = MX_GRAY_COLOR;
        [self.textField reloadInputViews];
        UIView *textFView = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenHeight-44-KSafeAreaTopHeight, kScreenWidth, 44)];
        textFView.backgroundColor = [UIColor whiteColor];
        UIView *textbgFV = [[UIView alloc]initWithFrame:CGRectMake(10, 5, kScreenWidth - 5 - 84, 34)];
        textbgFV.backgroundColor = MX_GRAY_COLOR;
        [textFView addSubview:textbgFV];
         [textFView addSubview:self.textField];
        [self addSubview:textFView];

        UIButton *sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
        sendButton.frame = CGRectMake(kScreenWidth - 88, 0, 88, 44);
        [sendButton setTitle:@"发送" forState:UIControlStateNormal];
        [sendButton setTitleColor:MX_TEXT1_COLOR forState:UIControlStateNormal];
        [sendButton addTarget:self action:@selector(sendClick:) forControlEvents:UIControlEventTouchUpInside];
        [textFView addSubview:sendButton];
        
    }
    return self;
}

#pragma mark - 上下拉刷新事件 -
- (void)addHeaderRefresh{
    //默认【下拉刷新】
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    //默认【上拉加载】
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
}

-(void)refresh{
    self.currentPage = 1;
    
    [self.paramsArr removeAllObjects];
    [self getMessageCommentsRequest];
}

-(void)loadMore{
    self.currentPage ++;
    [self getMessageCommentsRequest];
}

-(void)setMessages_id:(NSString *)messages_id{
    _messages_id = messages_id;
    
    [self refresh];
}

-(void)sendClick:(UIButton *)button{
    [self sendMessageCommentsRequest];
    [self.textField resignFirstResponder];
}

#pragma mark - UITextFieldDelegate -
/// 设置自定义键盘后，delegate 不会被调用？
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSLog(@"%@", [textField.text stringByReplacingCharactersInRange:range withString:string]);
    
    return YES;
}

#pragma mark - UITableViewDelegate -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_paramsArr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MXCommentsCell *cell = [MXCommentsCell cellWithTableView:tableView];
     MXCommentsModel *model = [MXCommentsModel mj_objectWithKeyValues:_paramsArr[indexPath.row]];
    cell.model = model;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
}

#pragma mark - 懒加载 -
-(NSMutableArray *)paramsArr{
    if (!_paramsArr) {
        _paramsArr = [[NSMutableArray alloc]init];
    }
    return _paramsArr;
}

- (NSMutableDictionary *)dicParams {
    if (!_dicParams) {
        _dicParams = [NSMutableDictionary dictionary];
    }
    [self initdicParams];
    return _dicParams;
}
- (void)initdicParams {
    _dicParams[@"messages_id"] = self.messages_id;
    _dicParams[@"pageNum"] = [@(self.currentPage) description];
    _dicParams[@"pageSize"] = @"10";
}

- (NSMutableDictionary *)sendDicParams {
    if (!_sendDicParams) {
        _sendDicParams = [NSMutableDictionary dictionary];
    }
   
    return _sendDicParams;
}

#pragma mark - 网络请求 -

-(void)getMessageCommentsRequest{
    [SVProgressHUD show];

    [[MXHttpManagerClass HttpRequstManager] PostURL:getMessageComments params:self.dicParams isHearderparam:YES success:^(NSInteger code, id result) {
        [SVProgressHUD dismiss];
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        if (code == 0) {
            
            NSLog(@"%@",result);
            NSArray *messArr = result[@"message"];
            if ([messArr count] == 0) {
                self.tableView.mj_footer = nil;
            }else{
                self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
            }
            
     
            for (id res in result[@"message"]) {
                [self.paramsArr addObject:res];
            }
            [self.tableView reloadData];
        }else{
            [SVProgressHUD showImage:NULL_IMAGE status:@"参数错误"];
        }
        
    } fail:^(NSError *error) {
        [SVProgressHUD dismiss];
        NSLog(@"%@",error);
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
    
}

-(void)sendMessageCommentsRequest{
    [SVProgressHUD show];

    self.sendDicParams[@"messages_id"] = self.messages_id;
    self.sendDicParams[@"comments_info"] = self.textField.text;
    self.sendDicParams[@"user_id"] = [MXUserMessageTool message].user_id;
    
    [[MXHttpManagerClass HttpRequstManager] PostURL:sendMessageComments params:self.sendDicParams isHearderparam:YES success:^(NSInteger code, id result) {
        [SVProgressHUD dismiss];
        
        if (code == 0) {
            NSLog(@"%@",result);
            self.commentsBlock();
            [self.paramsArr removeAllObjects];
            self.textField.text = @"";
            [self getMessageCommentsRequest];
        }else{
            [SVProgressHUD showImage:NULL_IMAGE status:@"参数错误"];
        }
        
    } fail:^(NSError *error) {
        [SVProgressHUD dismiss];
        NSLog(@"%@",error);
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
    
}


@end
